package com.ng.sys.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ng.common.log.annotation.SysLog;
import com.ng.common.security.SecurityUtils;
import com.ng.common.utils.Constant;
import com.ng.common.utils.DesUtils;
import com.ng.common.utils.MD5Utils;
import com.ng.common.utils.PageUtils;
import com.ng.common.utils.R;
import com.ng.common.validator.Assert;
import com.ng.common.validator.ValidatorUtils;
import com.ng.common.validator.group.AddGroup;
import com.ng.common.validator.group.UpdateGroup;
import com.ng.sys.entity.SysUserEntity;
import com.ng.sys.form.PasswordForm;
import com.ng.sys.form.ResetPassForm;
import com.ng.sys.service.SysUserRoleService;
import com.ng.sys.service.SysUserService;

/**
 * 系统用户
 * 
 * @author lyf
 * @email liuyf@gs-softwares.com
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController  {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
 
 
	@Autowired
	private SecurityUtils authUtils ;
 



	/**
	 * 所有用户列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:user")
	public R<PageUtils> list(SysUserEntity entity ,PageUtils page){
		//只有超级管理员，才能查看所有管理员列表
//		if(!getUserId().equals(Constant.SUPER_ADMIN)){
//			params.put("createUserId", getUserId());
//		}
		PageUtils pageData = sysUserService.queryPage(entity , page);

		return R.ok(PageUtils.class).setData( pageData);
	}

	/**
	 * 所有用户列表
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/listAll")
	@RequiresPermissions("sys:user")
	public R<List> listAll(){
		List<SysUserEntity> resultEntitys = new ArrayList<>();
		List<SysUserEntity> userEntities = sysUserService.list(null);
		//排查admin用户
		if(userEntities!=null){
			resultEntitys = userEntities.stream().filter(t->!t.getUserId().equals("admin")).collect(Collectors.toList());
		}else{
			resultEntitys = userEntities;
		}
		return R.ok(List.class).setData(resultEntitys);
	}


	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
//	@RequiresPermissions("sys:user")
	public R<SysUserEntity> info(){
		SysUserEntity  user = authUtils.getCurrentUser();
//		if(user!=null && user.getRoleId()!=null ){
//			String[] str = user.getRoleId().split(",");
//			user.setRoleIdList(Arrays.asList(str));
//		}
		return R.ok(SysUserEntity.class).setData(user);
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	public R<Object> password(@RequestBody PasswordForm form){
		Assert.isBlank(form.getNewPassword(), "新密码不为能空");
		
		//解密
		String o_pass = DesUtils.desEncrypt(form.getPassword()) ;// RsaUtils.decryptByPrivateKey(form.getPassword());
		if(o_pass == null) {
			R.error("原密码不正确");
		}
		String n_pass =  DesUtils.desEncrypt(form.getNewPassword()) ;// RsaUtils.decryptByPrivateKey(form.getNewPassword());
		if(n_pass == null) {
			R.error("新密码格式不正确");
		}
		SysUserEntity user = authUtils.getCurrentUser();
		
		//sha256加密
		String password = MD5Utils.md5Pass(o_pass, user.getSalt()) ;// new Sha256Hash(o_pass, getUser().getSalt()).toHex();
		//sha256加密
		String newPassword = MD5Utils.md5Pass(n_pass, user.getSalt()) ;//new Sha256Hash(n_pass, getUser().getSalt()).toHex();
				
		//更新密码
		boolean flag = sysUserService.updatePassword(user.getUserId(), password, newPassword);
		if(!flag){
			return R.error("原密码不正确");
		}
		
		return R.ok();
	}



	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@RequiresPermissions("sys:user")
	public R<SysUserEntity> info(@PathVariable("userId") String userId){
		SysUserEntity user = sysUserService.getById(userId);
		if(user!=null){
            //获取用户所属的角色列表
			List<String> stringList = sysUserRoleService.queryRoleIdList(user.getUserId());
            user.setRoleIdList(stringList);
        }
       
		
		return R.ok(SysUserEntity.class).setData(user);
	}
  
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R<Object> save(@RequestBody SysUserEntity user){
		 
		ValidatorUtils.validateEntity(user, AddGroup.class);
		//密码解密
		String pass = DesUtils.desEncrypt(user.getPassword()) ;// RsaUtils.decryptByPrivateKey(user.getPassword());
		if(pass == null) {
			return R.error("密码不能为空");
		}
		user.setPassword(pass);
		
		sysUserService.saveUser(user);
		return R.ok();
	}
    
  

	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PostMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R<Object> update(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, UpdateGroup.class);
		
		//admin用户除了自己可以修改以外,其他都不允许修改
		//另外,自己不可以直接在这里修改自己的密码
		SysUserEntity currUser = authUtils.getCurrentUser();
		String loginUserId = currUser.getUserId();
		if(user.getUserId().equals(loginUserId) && user.getPassword() != null && !user.getPassword().trim().isEmpty()) {
			return R.error("当前用户不可以直接在此重置自己的密码!");
		}
		
		//当前用户非admin 不可以修改admin
		if(!loginUserId.equals(Constant.SUPER_ADMIN) && user.getUserId().equals(Constant.SUPER_ADMIN)) {
			return R.error("普通用户不可以修改超管用户信息");
		}
		 
		
		//user.setCreateUserId(getUserId());
		sysUserService.update(user);
		
		return R.ok();
	}
	/**
	 * 修改用户信息 （用户维护信息）
	 */
 	@SysLog("保存用户信息")
	@PostMapping("/updateInfo") 
	public R<Object> updateInfo(@RequestBody SysUserEntity user){
		 
 		SysUserEntity currUser = authUtils.getCurrentUser();
		String loginUserId = currUser.getUserId();
		//用户只能修改自己的信息
		if(!user.getUserId().equals(loginUserId) ) {
			return R.error("当前用户只能修改自己的信息");
		}
		user.setPassword(null);
		user.setUserNo(currUser.getUserNo());
		  
		user.setSalt(null);
		user.setUpdateTime(new Date());
		user.setStatus(null);
		 
		sysUserService.updateById(user);
		return R.ok();
	} 

	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@PostMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R<Object> delete(@RequestBody String[] userIds){
		if(ArrayUtils.contains(userIds, Constant.SUPER_ADMIN)){
			return R.error("系统管理员不能删除");
		}
		SysUserEntity currUser = authUtils.getCurrentUser();
		if(ArrayUtils.contains(userIds, currUser.getUserId())){
			return R.error("当前用户不能删除");
		}
		
		sysUserService.deleteBatch(userIds);
		
		return R.ok();
	}
	 
	
	/**
	 * 密码重置 前提<br>
	 * 1、当前用户不能重置 超管密码<br>
	 * 2、当前用户不能重置自己密码<br>
	 * @param form 用户ID
	 *
	 * @return
	 */
	@SysLog("重置账号密码")
	@PostMapping("/resetPass")
	@RequiresPermissions("sys:user:resetPass")
	public R<Object> resetPass(@RequestBody ResetPassForm form ) {
		//String userId , String newPass
		Assert.isNull(form, "用户不能为空");
		
		String userId = form.getUserId();
		String newPass = form.getNewPass();
		
		Assert.isBlank(userId, "用户不能为空");
		Assert.isBlank(newPass, "密码不能为空");
		
		//拿到当前用户
		SysUserEntity currUser = authUtils.getCurrentUser();
		String currUserId = currUser.getUserId();
		
		
		if(currUserId.equals(userId)&& !Constant.SUPER_ADMIN.equals(currUserId)) {
			return R.error("当前用户不能重置自己的密码");
		}
		
		//密码解密后根据盐值加密
		String dePass = DesUtils.desEncrypt(newPass) ;// RsaUtils.decryptByPrivateKey(newPass);
		if(dePass == null) {
			return R.error("密码异常");
		} 
		
		// 拿到传过来的用户
		SysUserEntity user = sysUserService.getById(userId);
		
		Assert.isNull(user, "用户不存在");
		
		if(user.getUserId().equals(Constant.SUPER_ADMIN) && !Constant.SUPER_ADMIN.equals(currUserId)) {//只有admin能修改admin的密码
			return R.error("不能重置超管用户密码");
		}
		
		String password = MD5Utils.md5Pass(dePass, user.getSalt()) ;// new Sha256Hash(newPass, getUser().getSalt()).toHex(); 
		
		//重置
		sysUserService.resetPass(userId, password);
		
		return R.ok();
	}


	/**
	 * 用户信息
	 */
	@GetMapping("/userName/{userId}") 
	public R<String> userName(@PathVariable("userId") String userId) {
		 
		String name = "" ;
		if(StringUtils.isNotBlank(userId))  {
			if(userId.equals(Constant.SUPER_ADMIN)) {
				name = Constant.SUPER_ADMIN;
			} else {
				SysUserEntity user = sysUserService.getById(userId);
				if(user != null) {
					name = user.getUsername();
				}
			}
		}
		
	   
		return R.ok(String.class).setData(name);
	}


}
